<?php
/**
 * Created by PhpStorm.
 * User: pc
 * Date: 2024/1/19
 * Time: 16:22
 */

namespace app\common\helper;


use app\models\SetHistory;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;
use yii\helpers\Json;

class HistoryHelper
{
    protected static $obj;
    public static function getInstance(){
        return self::$obj instanceof HistoryHelper ? self::$obj : self::$obj = new self();
    }

    protected $obj_list = [];
    protected $key = 'openid';
    protected $value = '';

    /**
     * @return string
     */
    public function getKey()
    {
        return $this->key;
    }

    /**
     * @param $key
     * @return $this
     */
    public function setKey($key)
    {
        $this->key = $key;
        return $this;
    }

    public function addObj($obj){
        $key = $this->key;
        if(empty($this->value) || ($obj->$key == $this->value)){
            $this->obj_list[] = $obj;
            $this->value = $obj->$key;
        }
        return $this;
    }

    public function save(){
        if(!empty($this->obj_list)){
            $data = [];
            foreach ($this->obj_list as $obj){
                /**
                 * @var $obj ActiveRecord
                 */
                $data[$obj->formName()] = $obj->toArray();
            }
            $model = $this->getModel();
            $model->data_log = Json::encode($data);
            return $model->save();
        }
        return true;
    }

    protected function getModel(){
        $model = SetHistory::find()->andWhere(['openid'=>$this->value])->one();
        if(empty($model)){
            $model = new SetHistory();
            $model->openid = $this->value;
            $model->save();
        }
        return $model;
    }
}